package com.campus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.common.config.CodeConfig;
import com.campus.entity.*;
import com.campus.entity.File.File;
import com.campus.entity.Honor.Honor;
import com.campus.entity.Honor.HonorFile;
import com.campus.entity.Honor.HonorStudent;
import com.campus.entity.vo.File.FileVo;
import com.campus.service.*;
import com.campus.util.CopyPropertiesUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author: AlaskaBoo
 * @Date: 2022-10-27 19:58
 **/
@RestController
@RequestMapping("/api/honor")
@Transactional
public class HonorController {
    @Autowired
    private HonorFileService honorFileService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private HonorStudentService honorStudentService;
    @Autowired
    private HonorService honorService;
    @Autowired
    private FileService fileService;
    @Autowired
    private UploadService uploadService;

    @Value("${qiniu.prefix}")
    private String prefix;

    /**
     * 添加荣誉
     *
     * @param id
     * @param honor
     * @return
     */
    @PostMapping("/{id}")
    @CacheEvict(value = "Honor", allEntries =true)
    public ResultBody saveHonor(@PathVariable("id") Long id, @NotNull @RequestBody Honor honor) {
        //1.保存荣誉
        honor.setUploadTime(new Date());
        honorService.save(honor);
        //2.获取用户的id
        HonorStudent honorStudent = new HonorStudent();
        honorStudent.setHonorId(Long.valueOf(honor.getId()));
        honorStudent.setStudentId(id);
        //3.写入数据库
        honorStudentService.save(honorStudent);
        return ResultBody.ok().data("honorStudent", honorStudent).data("honor", honor);
    }

    /**
     * 根据学生查询荣誉
     *
     * @param id
     * @return
     */
    @GetMapping("/student/{id}")
    @Cacheable(value = "Honor")
    public ResultBody selectTeacherById(@PathVariable Long id) {
        //1.获取学生信息
        Student studentInfo = studentService.getById(id);
        if ((studentInfo == null)) {
            return ResultBody.error().message(CodeConfig.QUERY_FAIL.message);
        }
        //2.获取学生荣誉
        List<Honor> honorList = honorService.list(new QueryWrapper<Honor>().inSql("id", "select honor_id from t_honor_student where student_id=" + studentInfo.getId()));
        honorList.forEach(honor -> {
            List<File> fileList = fileService.list(new QueryWrapper<File>().inSql("id", "select file_id  from t_honor_file where honor_id=" + honor.getId()));
            honor.setFileList(fileList);
        });

        studentInfo.setHonorList(honorList);
        return ResultBody.ok().data("studentInfo", studentInfo);
    }

    /**
     * 修改荣誉
     *
     * @param honor
     * @return
     */
    @PutMapping
    @CacheEvict(value = "Honor", allEntries =true)
    public ResultBody updateHonor(@RequestBody Honor honor) {
        if (honor.getId() != null) {
            honor.setUpdateTime(new Date());
            honorService.updateById(honor);
        } else {
            return ResultBody.error(CodeConfig.ERROR_Information);
        }
        return ResultBody.ok().data("honor", honor);
    }

    /**
     * 荣誉上传
     *
     * @param id
     * @param multipartFile
     * @param remark
     * @return
     */
    @PostMapping("/upload/{id}")
    @CacheEvict(value = "Honor",allEntries =true)
    public ResultBody upload(@PathVariable Long id, @RequestParam("file") MultipartFile multipartFile, String remark) {
        //获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        long fileSize = multipartFile.getSize();
        //获取文件后缀
        String suffix = originalFilename.substring(lastIndexOf + 1);
        //使用UUID随机产生文件名称，防止同名文件覆盖
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid + "." + suffix;
        try {
            uploadService.upload2Qiniu(multipartFile.getBytes(), fileName);
            String url = prefix + "/" + fileName;
            File file = new File();
            //数据落库
            file.setUuidName(uuid);
            file.setUploadTime(new Date());
            file.setOldFilename(originalFilename);
            file.setNewFilename(fileName);
            file.setSize(fileSize);
            file.setPath(url);
            file.setType(suffix);
            file.setRemark(remark);
            fileService.save(file);
            File fileInfo = fileService.lambdaQuery().in(File::getUuidName, uuid).one();
            HonorFile honorFile = new HonorFile();
            honorFile.setFileId(Long.valueOf(fileInfo.getId()));
            honorFile.setHonorId(id);
            honorFileService.save(honorFile);

            return ResultBody.ok().data("url", url).data("honorFile", honorFile).message(CodeConfig.PIC_UPLOAD_SUCCESS.message);
        } catch (Exception e) {
            e.printStackTrace();
            //图片上传失败
            return ResultBody.error().message(CodeConfig.PIC_UPLOAD_FAIL.message);
        }

    }

    /**
     * 根据荣誉查询文件
     */
    @GetMapping("/student/upload/id={id}")
    @Cacheable(value = "Honor")
    public ResultBody selectHonorFileById(@PathVariable Long id) {
        //1.获取荣誉信息
        Honor honorInfo = honorService.getById(id);
        if (honorInfo == null) {
            return ResultBody.error().message(CodeConfig.QUERY_FAIL.message);
        }
        //2.获取文件
        List<File> fileList = fileService.list(new QueryWrapper<File>().inSql("id", "select file_id from t_honor_file where honor_id=" + honorInfo.getId()));
        List<FileVo> collect = fileList.stream().map(file -> CopyPropertiesUtils.copyProperties(file, FileVo.class)).collect(Collectors.toList());
        return ResultBody.ok().data("fileList", collect);
    }

    /**
     * 删除荣誉图片
     */
    @DeleteMapping("/delete/{id}")
    @CacheEvict(value = "Honor", allEntries =true)
    public ResultBody deleteImg(@PathVariable Long id, @RequestParam("file") String[] fileName) {

        try {
            File fileInfo = fileService.lambdaQuery().in(File::getNewFilename, fileName).one();
            honorFileService.remove(new QueryWrapper<HonorFile>().in("honor_id", id).in("file_id", fileInfo.getId()));
            fileService.remove(new QueryWrapper<File>().in("new_filename", fileName));
            uploadService.deleteFileFromQiniu(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            //图片删除失败
            return ResultBody.error().message(CodeConfig.PIC_DELETE_FAIL.message);
        }
        return ResultBody.ok().data("url", prefix + "/" + fileName).message(CodeConfig.PIC_DELETE_FAIL.message);
    }

}
